<script>
/**
 * @desc 环形图
 */

import DoughnutChartItem from './item'
import { numberFixed, hsla2rgba } from '@/utils'

export default {
  name: 'doughnut-chart',

  props: {
    list: {
      type: Array,
      default: () => []
    },
    size: {
      type: Number,
      default: 200
    },
    borderWidth: {
      type: Number,
      default: 20
    }
  },

  components: { DoughnutChartItem },

  computed: {
    chartData() {
      const total = this.list.reduce((pre, curr) => pre + curr, 0)
      const hue = numberFixed(360 / this.list.length)
      return this.list
        .reduce((pre, curr, index) => {
          const last = pre[pre.length - 1]
          const item = {
            percent: numberFixed(curr / total + (last ? last.percent : 0), {
              count: 4,
              type: 'ceil'
            }),
            color: hsla2rgba(hue * index, 0.82, 0.67, 1)
          }
          return [...pre, item]
        }, [])
        .reverse()
    }
  }
}
</script>

<template>
  <div
    :style="{width: size+'px',height: size+'px'}"
    class="doughnut-chart-container"
  >
    <doughnut-chart-item
      :color="v.color"
      :key="i"
      :percent="v.percent"
      :size="size"
      v-for="(v,i) in chartData"
    />
  </div>
</template>

<style lang="scss">
.doughnut-chart-container {
  position: relative;
}
</style>
